/**
 * HeartBeat
 * 上报并产生心跳信号的工具类
 * 目前心跳接口在config.properties中HBInterface定义
 * 统计作业开始执行时调用
 * @author jiyongtian 2015.02.05
 **/
package net.tycmc.cty.ctyms.timejob.function.monitore;

import java.io.BufferedReader;
import java.io.IOException;
//import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
//import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
//import java.util.HashMap;
import java.util.Map;

//import javax.xml.parsers.ParserConfigurationException;
//import javax.xml.parsers.SAXParser;
//import javax.xml.parsers.SAXParserFactory;

import net.tycmc.bulb.common.util.MapGetter;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.log4j.Logger;
//import org.codehaus.jackson.JsonParseException;
//import org.codehaus.jackson.map.JsonMappingException;
//import org.codehaus.jackson.map.ObjectMapper;
//import org.xml.sax.Attributes;
//import org.xml.sax.SAXException;
//import org.xml.sax.helpers.DefaultHandler;

import com.tycmc.functions.util.DynamicReadConfig;
import com.tycmc.functions.util.StringUtil;

public class HeartBeat {
	private static Logger logger = Logger.getLogger("HeartBeat");
	private  String hbInterface = null;
	
	public HeartBeat(){
		try {
			this.hbInterface = DynamicReadConfig.getConfigProperty("config.properties", "HBInterface");
//			System.out.println("读取的心跳接口"+this.hbInterface);
		} catch (ConfigurationException e) {
			logger.info("读取config.properties定义的心跳接口时发生异常");
		}
	}
	
	
	/**
	 * 产生并上报心跳信号
	 * @param param 作业信息 至少应该有这两个key：jobID——向监控软件注册时生成的ID值，jobName——作业名称
	 * 
	 **/
	public boolean produceAndReportHeateBeat(Map<String,Object> param){
		boolean flag = false;
		if(StringUtil.isValid(this.hbInterface)){
			String jobID = MapGetter.getString(param,"jobID");
			String jobName = MapGetter.getString(param, "jobName");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				URL	url = new URL(this.hbInterface.replaceAll("ID", jobID));
				HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
			    httpConn.setRequestMethod("GET");
			    httpConn.setRequestProperty("Accept", "application/json");
			    httpConn.setConnectTimeout(1000);
			    BufferedReader bufReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
		    	StringBuffer strBuf = new StringBuffer();
		    	String output;
		    	while((output=bufReader.readLine())!=null){
		    		strBuf.append(output);
		    	}
		    	String reJson = strBuf.toString();
				if(StringUtil.isValid(reJson)){
					if(reJson.indexOf("1")>-1){
						logger.info(sdf.format(new Date())+"   "+jobName + "产生并上报心跳信号成功！");
					}else{
						logger.info(sdf.format(new Date())+"   "+jobName + "产生并上报心跳信号失败！");
					}
				}else{
					logger.info(sdf.format(new Date())+"   "+jobName + "产生并上报心跳信号失败！");
				}
			} catch (MalformedURLException e) {
//				System.out.println(sdf.format(new Date())+"   "+jobName + "产生并上报心跳信号时发生异常（MalformedURLException）！异常信息如下：");
				e.printStackTrace();
				logger.info(e.getMessage());
			} catch (IOException e1){
//				System.out.println(sdf.format(new Date())+"   "+jobName + "产生并上报心跳信号时发生异常（IOException）！异常信息如下：");
				e1.printStackTrace();
				logger.info(e1.getMessage());
			}
		}
		return flag;
	}

	/**
	 * 产生并上报心跳信号
	 * @param param 作业信息 至少应该有这两个key：jobID——向监控软件注册时生成的ID值，jobName——作业名称
	 * 
	 *
	public boolean produceAndReportHeateBeat(Map<String,Object> param){
		boolean flag = false;
		if(StringUtil.isValid(this.hbInterface)){
			String jobID = MapGetter.getString(param,"jobID");
			String jobName = MapGetter.getString(param, "jobName");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
			    URL	url = new URL(this.hbInterface.replaceAll("ID", jobID));
			    URLConnection conn = url.openConnection();
			    conn.setConnectTimeout(5000);//超时时间为5秒
			    conn.setDoOutput(true);
				conn.setDoInput(true);
				Map<String,Object> map = this.parseXML(conn.getInputStream());
				if(null!=map && !map.isEmpty()){
					if(MapGetter.getString(map, "int").indexOf("1")>-1){
						logger.info(sdf.format(new Date())+"   "+jobName + "产生并上报心跳信号成功！");
					}else{
						logger.info(sdf.format(new Date())+"   "+jobName + "产生并上报心跳信号失败！");
					}
				}else{
					logger.info(sdf.format(new Date())+"   "+jobName + "产生并上报心跳信号失败！");
				}
			} catch (MalformedURLException e) {
//				System.out.println(sdf.format(new Date())+"   "+jobName + "产生并上报心跳信号时发生异常（MalformedURLException）！异常信息如下：");
				e.printStackTrace();
				logger.info(e.getMessage());
			} catch (IOException e1){
//				System.out.println(sdf.format(new Date())+"   "+jobName + "产生并上报心跳信号时发生异常（IOException）！异常信息如下：");
				e1.printStackTrace();
				logger.info(e1.getMessage());
			}
		}
		return flag;
	}
	private Map<String, Object> parseXML(InputStream in) {
		SAXParser saxparser;
		HeartBeatHandler hbh = new HeartBeatHandler();
		try {
			saxparser = SAXParserFactory.newInstance().newSAXParser();
			saxparser.parse(in, hbh);
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return hbh.map;
	}
	class HeartBeatHandler extends DefaultHandler{
		private String preTag = null;
		Map<String,Object> map = new HashMap<String,Object>();
		@Override
		public void startElement(String uri,String localName,String qName,Attributes attributes) throws SAXException{
			preTag = qName;
		}
		@Override
		public void endElement(String uri,String localName,String qName) throws SAXException{
			preTag = null;
		}
		@Override
		public void characters(char[] ch,int start,int length) throws SAXException{
			if(null != preTag){
				String content = new String(ch,start,length);
				if(preTag.equals("int")){
					map.put("int", content);
				}
			}
		}
	}
	*/
}
